﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
using System.Windows.Media;

namespace SqlMiM.Common.Converters
{
    public class BrushOpacityConverter : IValueConverter
    {
        // Methods
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if ((value != null) && (parameter != null))
            {
                double naN = double.NaN;
                Type c = parameter.GetType();
                if (typeof(double).IsAssignableFrom(c))
                {
                    naN = (double)parameter;
                }
                else if (typeof(string).IsAssignableFrom(c) && !double.TryParse((string)parameter, NumberStyles.Float | NumberStyles.AllowThousands, culture, out naN))
                {
                    naN = double.NaN;
                }
                if (double.IsNaN(naN))
                {
                    return value;
                }
                Brush brush = (Brush)value;
                if (naN > 1.0)
                {
                    naN = 1.0;
                }
                else if (naN < 0.0)
                {
                    naN = 0.0;
                }
                brush = brush.Clone();
                brush.Opacity = naN;
                brush.Freeze();
                value = brush;
            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException("BrushOpacityConverter.ConvertBack not implemented.");
        }
    }

}
